package com.payne;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.UUID;

public class ZolSpider3 implements PageProcessor {

    private static String url="http://desk.zol.com.cn/";

    private Site site=Site.me()
            .setRetryTimes(3)
            .setSleepTime(3000)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50");


    public void process(Page page) {

        if(url.equals(page.getUrl().toString())){
            List<String> all = page.getHtml().xpath("//ul[@id=\"newPicList\"]/li/a/@href").all();
            for (String s : all) {
                //http://desk.zol.com.cn/bizhi/5132_63536_2.html
                ///bizhi/7499_92923_2.html
                s="http://desk.zol.com.cn"+s;
            }
            page.addTargetRequests(all);
        }else {
            String s = page.getHtml().xpath("//*[@id=\"bigImg\"]/@src").get();
            try {
                URL url = new URL(s);
                URLConnection urlConnection = url.openConnection();
                InputStream inputStream = urlConnection.getInputStream();
                byte[] buf=new byte[1024];
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                int len;
                while ((len=inputStream.read(buf))!=-1){
                    byteArrayOutputStream.write(buf,0,len);
                }
                inputStream.close();
                byteArrayOutputStream.close();
                String uuid = UUID.randomUUID().toString();
                File file = new File("F:/test/" + uuid + ".jpg");
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                fileOutputStream.write(byteArrayOutputStream.toByteArray());
                fileOutputStream.close();

            } catch (Exception e) {
                e.printStackTrace();

            }


        }

    }

    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new ZolSpider3()).addUrl(url).thread(5).run();
    }

}
